package cn.bonoon.services;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.batatasframework.chart.ChartCell;
import org.batatasframework.chart.ChartDefinition;
import org.batatasframework.chart.ChartManager;
import org.batatasframework.chart.ChartQueryResult;
import org.batatasframework.chart.ChartRow;
import org.batatasframework.chart.ChartValueReader;
import org.batatasframework.chart.columns.ChartColumnAxis;
import org.batatasframework.chart.data.ChartData;
import org.batatasframework.common.ParameterReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import cn.bonoon.core.ChartManagedService;
import cn.bonoon.kernel.support.IOperator;
import cn.bonoon.kernel.support.services.ServiceSupport;

@Service
@Transactional(readOnly = true)
public class ChartManagedServiceImpl extends ServiceSupport implements ChartManagedService {
	
	@Autowired
	private ChartManager chartManager;
	
	@Override
	public ChartDefinition load(IOperator user, String catalog, String key) {
		return chartManager.get(catalog, key);
	}
	
	@Override
	public ChartData load(IOperator user, String catalog, String key, ParameterReader reader) {
		
		ChartDefinition definition = chartManager.get(catalog, key);
		ChartValueReader cvReader = definition.getReader();
		ChartQueryResult items = cvReader.read(entityManager, user, reader);
		
		Assert.notNull(items, "没有数据！");
		
		ChartColumnAxis axis = items.getAxis();
		ChartData data;
		if(null == axis){
			axis = definition.getAxis();
		}
		
		data = new ChartData(axis, definition);
		
		if(items.isGroupable()){
			Map<String, ChartRow> rowMapped = new HashMap<>();
			for(Object obj : items){
				Object[] values = (Object[])obj;
				ChartCell axisCell = axis.newCell();
				axisCell.read(values);
				String rowKey = axisCell.toString();
				
				ChartRow row = rowMapped.get(rowKey);
				if(null == row){
					row = definition.newRow();
					rowMapped.put(rowKey, row.read(axisCell));
				}
				row.read(values);
			}
			data.addData(rowMapped.values());
		}else{
			List<ChartRow> rows = new ArrayList<>();
			for(Object obj : items){
				Object[] values = (Object[])obj;
				ChartRow row = definition.newRow();
				rows.add(row.read(axis, values).read(values));
			}
			data.addData(rows);
		}
		
		return data.finish();
	}

}
